package com.chatgpt.platformbasedchatgpt.controller;


import com.chatgpt.platformbasedchatgpt.dao.User;
import com.chatgpt.platformbasedchatgpt.dao.UserDto;
import com.chatgpt.platformbasedchatgpt.service.SendMailService;
import com.chatgpt.platformbasedchatgpt.service.UserService;
import com.chatgpt.platformbasedchatgpt.utils.CheckCode;
import com.chatgpt.platformbasedchatgpt.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Chat
 * @since 2023-12-03
 */
@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    SendMailService mailService;

    @PostMapping("/register")
    public CommonResult register(@RequestBody UserDto userDto){
        User user = userDto.getUser();
        String code = userDto.getCode();
        String checkCode = redisTemplate.opsForValue().get(user.getAccount());
        if(checkCode.equals(code)){
            int i = userService.insertUser(user);
            if(i==1){
                return CommonResult.success("注册成功！");
            }else if(i==2){
                return CommonResult.failed("注册失败，用户已存在！");
            }else return CommonResult.failed("注册失败");
        }else return CommonResult.failed("验证码错误！");
    }

    @PostMapping("/login")
    public CommonResult<User> login(@RequestBody User user){
        User user1 = userService.getUser(user);
        if(user1!=null){
            return CommonResult.success(user1);
        }else {
            return  CommonResult.failed("登陆失败！");
        }

    }

    @GetMapping("/getCode")
    public CommonResult getCode(String account){
        try{
            String code =  CheckCode.getCode();
            mailService.sendSimpleMail(account,code);
            redisTemplate.opsForValue().set(account,code,10, TimeUnit.MINUTES);
            return CommonResult.success("发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.success("发送失败");
        }
    }
}

